<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               v-model:page="page"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.reportedloss_delete"
                   @click="handleDelete">删 除
        </el-button>

        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   v-if="permission.reportedloss_edit"
                   @click="handleExport">导出
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/restaurant/reportedloss';
import { mapGetters } from 'vuex';
import { baseUrl } from '@/config/env';
import func from '@/utils/func';
import { getToken } from '@/utils/auth';
import { serialize } from '@/utils/util';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        column: [
          {
            label: '日期范围',
            hide: true,
            editDisplay: false, // 编辑隐藏
            addDisplay: false, // 新增隐藏
            prop: 'searchTime',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            search: true,
            searchSpan: 8,
            searchRange: true,
            disabledDate(time) {
              return time.getTime() > Date.now();
            }
          },
          {
            label: '日期',
            prop: 'declareDate',
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            rules: [{
              required: true,
              message: '请输入日期',
              trigger: 'blur'
            }]
          },
          {
            label: '报损用户',
            prop: 'userId',
            multiple: false,
            filterable: true,
            search: true,
            editDisabled: true, // 禁止编辑
            type: 'tree',
            dicUrl: baseUrl + '/restaurant/common/userAttendance',
            rules: [{
              required: true,
              message: '请输入报损用户',
              trigger: 'click'
            }],
            nodeClick: (data) => {
              this.form.userName = data.realName;
            }
          },
          {
            label: '区域',
            prop: 'areaId',
            multiple: false,
            filterable: true,
            type: 'tree',
            dicUrl: baseUrl + '/restaurant/area/tree?type=1',
            props: {
              label: 'title',
              value: 'value'
            },
            slot: true,
            checkStrictly: true,
            rules: [{
              required: true,
              message: '请输入区域',
              trigger: 'click'
            }],
            nodeClick: (data) => {
              this.form.areaName = data.title;
            }
          },
          {
            label: '物品类型',
            prop: 'itemType',
            type: 'select',
            dicUrl: baseUrl + '/blade-system/dict/dictionary?code=item_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [{
              required: true,
              message: '请输入物品类型',
              trigger: 'blur'
            }]
          },
          {
            label: '说明',
            prop: 'itemName',
            rules: [{
              required: false,
              message: '请输入说明',
              trigger: 'blur'
            }]
          },
          {
            label: '附件',
            prop: 'enclosure',
            type: 'upload',
            listType: 'picture-card',
            overHidden: true,
            width: '120',
            action: '/api/blade-resource/oss/endpoint/put-file',
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            rules: [{
              required: true,
              message: '请输入附件',
              trigger: 'blur'
            }]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            rules: [{
              required: false,
              message: '请输入备注',
              trigger: 'blur'
            }]
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.reportedloss_add, false),
        viewBtn: this.validData(this.permission.reportedloss_view, false),
        delBtn: this.validData(this.permission.reportedloss_delete, false),
        editBtn: this.validData(this.permission.reportedloss_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    async handleExport() {
      this.$confirm(`确定导出报损记录数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(`/api/restaurant/reportedloss/export?blade-auth=bearer ${getToken()}&` + serialize(this.query));
      });
    },
    rowSave(row, done, loading) {
      if (Array.isArray(row.enclosure)) {
        row.enclosure = func.join(row.enclosure);
      }
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      if (Array.isArray(row.enclosure)) {
        row.enclosure = func.join(row.enclosure);
      }
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
